package com.zjdiepu.www.manage.api.yw;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.BusiStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.LoanEditStatus;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.enums.type.SortFieldType;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessVoMapper;
import com.zjdiepu.www.ibiz.yw.IYwBusinessLoanEditService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessService;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwBusinessLoanEdit;
import com.zjdiepu.www.model.yw.ext.YwBusinessLoanEditExt;
import com.zjdiepu.www.model.yw.request.YwBusinessQueryRequest;
import com.zjdiepu.www.util.YwExtHelper;

/**
 * yw_贷款信息修改表Controller层<br/>
 * @author zhangzhengjian<br/>
 * @time 2017年10月16日 15时43分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "YwBusinessLoanEditController", produces="application/json;charset=UTF-8")
@Api(tags = {"yw_贷款信息修改表"}, produces="application/json;charset=UTF-8")
public class YwBusinessLoanEditController extends BaseController {
    @Resource
    private IYwBusinessLoanEditService ywBusinessLoanEditService;
    @Resource
    private YwBusinessVoMapper ywBusinessVoMapper;
    @Resource
    private IYwBusinessService ywBusinessService;
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: changeLoanHistoryList  <br/>
     * @Description: 修改贷款历史信息 <br/>
     * @param ywBusinessQueryRequest
     * @param changeLoanType 1:贷款信息修改A 2：贷款信息修改2
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改贷款历史信息",response = YwBusiness.class, httpMethod="POST")
    @RequestMapping(value = "changeLoanHistoryList", method = RequestMethod.POST)
    public ApiResponse changeLoanHistoryList(@Validated @ModelAttribute YwBusinessQueryRequest ywBusinessQueryRequest, @RequestParam(defaultValue="1")Integer changeLoanType){
    	SysUser currentUser = (SysUser)getCurrentUser();
		PageVo page = getPage(ywBusinessQueryRequest);
		ywBusinessQueryRequest.setBaseWhere();
		ywBusinessQueryRequest.setBankLoan(currentUser.getLoanBank());
        ywBusinessQueryRequest.setCodeUnits(currentUser.getCodeUnits());
        ywBusinessQueryRequest.setNeedLimit(true);
        
        Date applyTimeStartDate = ywBusinessQueryRequest.getApplyTimeStartDate();
        if(applyTimeStartDate != null) {
        	ywBusinessQueryRequest.setApplyTimeStart(DateUtil.truncAndAddDays(applyTimeStartDate, 0).getTime() / 1000);
        } 
        Date applyTimeEndDate = ywBusinessQueryRequest.getApplyTimeEndDate();
        if(applyTimeEndDate != null){
        	ywBusinessQueryRequest.setApplyTimeEnd(DateUtil.truncAndAddDays(applyTimeEndDate, 1).getTime() / 1000);
        }
        ywBusinessQueryRequest.setModifyLoanHistory(true);
        ywBusinessQueryRequest.addLoanEditStatuss(LoanEditStatus.SHEN_HE_1_BU_TONG_GUO.getCode()).addLoanEditStatuss(LoanEditStatus.SHEN_HE_2_BU_TONG_GUO.getCode())
        .addLoanEditStatuss(LoanEditStatus.SHEN_HE_1_TONG_GUO.getCode()).addLoanEditStatuss(LoanEditStatus.SHEN_HE_2_TONG_GUO.getCode());
        
        int records = ywBusinessLoanEditService.countMultiByExtForUpdateHistory(ywBusinessQueryRequest);
        page.setRecords(records);
        if (records > 0) {
            List<YwBusiness> ywBusinesss = ywBusinessLoanEditService.selectMultiByExtForUpdateHistory(ywBusinessQueryRequest);
            ywBusinessVoMapper.mapper(ywBusinesss);
            page.setRows(ywBusinesss);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }

    
    
    @ApiOperation(value = "提交yw_贷款信息修改表", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "saveLoan", method = RequestMethod.POST)
    public ApiResponse saveLoan(@Validated(Add.class) @ModelAttribute YwBusinessLoanEdit ywBusinessLoanEdit) {
    	AbstractSysUser currentUser = getCurrentUser();
    	ywBusinessLoanEdit.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywBusinessLoanEdit.setModifierName(currentUser.getName());
    	ywBusinessLoanEditService.saveOrUpdateLoan(ywBusinessLoanEdit,currentUser);
        return ApiResponse.success(true);
    }
    
    /**
     * @author zhangzhengjian <br/>
     * @Title: save  <br/>
     * @Description: 新增yw_贷款信息修改表 <br/>
     * @param ywBusinessLoanEdit
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增yw_贷款信息修改表", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute YwBusinessLoanEdit ywBusinessLoanEdit) {
    	AbstractSysUser currentUser = getCurrentUser();
    	ywBusinessLoanEdit.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywBusinessLoanEdit.setModifierName(currentUser.getName());
        ywBusinessLoanEditService.saveUpdateAndDelete(ywBusinessLoanEdit, OperateType.add);
        return ApiResponse.success(true);
    }

    /**
     * @author zhangzhengjian <br/>
     * @Title: remove  <br/>
     * @Description: 删除yw_贷款信息修改表<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除yw_贷款信息修改表", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywBusinessLoanEditService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author zhangzhengjian <br/>
     * @Title: disable  <br/>
     * @Description: 禁用yw_贷款信息修改表<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用yw_贷款信息修改表", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywBusinessLoanEditService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author zhangzhengjian <br/>
     * @Title: enable <br/>
     * @Description: 启用yw_贷款信息修改表<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用yw_贷款信息修改表", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywBusinessLoanEditService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author zhangzhengjian <br/>
     * @Title: modify  <br/>
     * @Description: 修改yw_贷款信息修改表 <br/>
     * @param ywBusinessLoanEdit
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改yw_贷款信息修改表", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute YwBusinessLoanEdit ywBusinessLoanEdit) {
    	AbstractSysUser currentUser = getCurrentUser();
    	ywBusinessLoanEdit.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywBusinessLoanEdit.setModifierName(currentUser.getName());
    	ywBusinessLoanEditService.saveUpdateAndDelete(ywBusinessLoanEdit, OperateType.edit);
        return ApiResponse.success(true);
    }

    /**
     * @author zhangzhengjian <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询yw_贷款信息修改表<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询yw_贷款信息修改表", response = YwBusinessLoanEdit.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       YwBusinessLoanEdit ywBusinessLoanEdit = ywBusinessLoanEditService.selectById(id);
       if(null == ywBusinessLoanEdit) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(ywBusinessLoanEdit);
    }
    
    /**
     * @author zhangzhengjian <br/>
     * @Title: list  <br/>
     * @Description: 条件查询yw_贷款信息修改表 <br/>
     * @param ywBusinessLoanEditExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询yw_贷款信息修改表",response = YwBusinessLoanEdit.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute YwBusinessLoanEditExt ywBusinessLoanEditExt){
        ywBusinessLoanEditExt.notDeleted();
        PageVo page = getPage(ywBusinessLoanEditExt);
        int records = ywBusinessLoanEditService.countByExt(ywBusinessLoanEditExt);
        page.setRecords(records);
        if (records > 0) {
            List<YwBusinessLoanEdit> dpBaseDataDictionaries = ywBusinessLoanEditService.selectByExt(ywBusinessLoanEditExt);
            page.setRows(dpBaseDataDictionaries);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    
    @ApiOperation(value = "条件查询业务信息",response = YwBusiness.class, httpMethod="POST", tags={"多表查询"})
    @RequestMapping(value = "multiList", method = RequestMethod.POST)
    public ApiResponse multiList(@Validated @ModelAttribute YwBusinessQueryRequest ywBusinessQueryRequest){
    	SysUser currentUser = (SysUser)getCurrentUser();
		PageVo page = getPage(ywBusinessQueryRequest);
		ywBusinessQueryRequest.setBaseWhere();
		ywBusinessQueryRequest.setBankLoan(currentUser.getLoanBank());
        YwExtHelper.initExt(ywBusinessQueryRequest, SortFieldType.SUBMIT_TIME);
//        ywBusinessQueryRequest.setBusiStatusLess(BusiStatus.CHU_SHEN_DAN_CHU_SHEN_ZHONG.getCode());
//        ywBusinessQueryRequest.setBusiStatusNqMore(BusiStatus.YIN_HANG_YI_FANG_KUAN.getCode());
//        @update2018-01-25      同已套打（不包括）之前，初审一审中（包括）之后
        ywBusinessQueryRequest.setBusiStatusLess(BusiStatus.CHU_SHEN_DAN_CHU_SHEN_ZHONG.getCode());
        ywBusinessQueryRequest.setBusiStatusNqMore(BusiStatus.HETONG_CONSTRACT_OK.getCode());
        ywBusinessQueryRequest.setCodeUnits(currentUser.getCodeUnits());
        ywBusinessQueryRequest.setNeedLimit(true);
        int records = ywBusinessLoanEditService.countMultiByExt(ywBusinessQueryRequest);
        page.setRecords(records);
        if (records > 0) {
            List<YwBusiness> ywBusinesss = ywBusinessLoanEditService.selectMultiByExt(ywBusinessQueryRequest);
            ywBusinessVoMapper.mapper(ywBusinesss);
            YwBusinessLoanEdit ywBusinessLoanEditParam = new YwBusinessLoanEdit();
            ywBusinessLoanEditParam.setDpStatus(DpStatus.NORMAL.getCode());
            for(YwBusiness ywBusiness : ywBusinesss) {
            	ywBusinessLoanEditParam.setLoanEditStatus(LoanEditStatus.YI_SHEN_QING.getCode());
            	ywBusinessLoanEditParam.setBusiId(ywBusiness.getId());
            	
            	YwBusinessLoanEdit ywBusinessLoanEditDb = ywBusinessLoanEditService.selectRefined(ywBusinessLoanEditParam);
            	if(ywBusinessLoanEditDb!=null){
	            	ywBusiness.setLoanEditStatus(ywBusinessLoanEditDb.getLoanEditStatus());
	            	ywBusiness.setHisLoanId(ywBusinessLoanEditDb.getHisLoanId());
	            	ywBusiness.setLoanEditId(ywBusinessLoanEditDb.getId());
            	} else {
            		
            		ywBusinessLoanEditParam.setLoanEditStatus(LoanEditStatus.SHEN_HE_2_SHEN_HE_ZHONG.getCode());
            		ywBusinessLoanEditDb=ywBusinessLoanEditService.selectRefined(ywBusinessLoanEditParam);
            		if(ywBusinessLoanEditDb != null) {
            			ywBusiness.setLoanEditStatus(ywBusinessLoanEditDb.getLoanEditStatus());
            			ywBusiness.setHisLoanId(ywBusinessLoanEditDb.getHisLoanId());
    	            	ywBusiness.setLoanEditId(ywBusinessLoanEditDb.getId());
            		}
            	}
            	
            }
            page.setRows(ywBusinesss);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
	}
}
